package com.cf.game.stage;

import com.cf.core.player.Player;
import com.cf.core.spirit.Spiriter;
import com.cf.game.message.BeatRequest;
import com.cf.game.stage.event.BeatEvent;
import com.cf.serialize.SmallRoomRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * +.
 * game-server-ClassRoomManager
 * 小房间管理器
 * 分发消息
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/8 上午 10:17
 */
@Slf4j
@Component
public class ClassRoomManager {

    private Map<String, ClassRoom> rooms = new ConcurrentHashMap();

    private Map<String, ClassRoom> userRooms = new ConcurrentHashMap();

    public void addRoom(ClassRoom classRoom, List<Player> players) {
        rooms.put(classRoom.getStageNum(), classRoom);
        players.forEach(player -> {
            userRooms.put(String.valueOf(player.getId()), classRoom);
        });
    }

    public void dispatchMessage(SmallRoomRequest smallRoomRequest) {

        String roomNum = smallRoomRequest.getRoomNum();
        ClassRoom classRoom = rooms.get(roomNum);
        if (classRoom == null) {
            log.warn("当前房间的游戏已经结束！【{}】,消息是【{}】", roomNum, smallRoomRequest);
            return;
        }

        Integer userId = smallRoomRequest.getUserId();
        Spiriter suitableSpiriter = classRoom.getSuitableSpiriter(userId);
        if (suitableSpiriter == null) {
            log.warn("未找到消息所对应的精灵！【{}】", smallRoomRequest);
            return;
        }

        //将消息转化为事件
        if (smallRoomRequest instanceof BeatRequest) {
            BeatEvent beatEvent = new BeatEvent(suitableSpiriter);
            classRoom.broadcastEvent(beatEvent);
        }

    }

    public void removeRoom(String roomNum, List<Player> players) {
        this.rooms.remove(roomNum);
        players.forEach(player -> {
            this.userRooms.remove(player.getId());
        });
    }
}
